// 主要JavaScript功能

document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // 座位选择功能 - 只在非购票页面初始化
    if (!window.location.pathname.includes('/book/')) {
        initSeatSelection();
    }
    
    // 电影推荐功能
    initMovieRecommendations();
    
    // 表单验证
    initFormValidation();
    
    // 动态加载效果
    initFadeInEffects();
});

// 座位选择功能
function initSeatSelection() {
    const seats = document.querySelectorAll('.seat:not(.sold):not(.disabled)');
    const selectedSeats = new Set();
    
    seats.forEach(seat => {
        seat.addEventListener('click', function() {
            const seatId = this.dataset.seatId;
            
            if (this.classList.contains('selected')) {
                this.classList.remove('selected');
                selectedSeats.delete(seatId);
            } else {
                this.classList.add('selected');
                selectedSeats.add(seatId);
            }
            
            updateSelectedSeatsDisplay(selectedSeats);
        });
    });
}

// 更新已选座位显示
function updateSelectedSeatsDisplay(selectedSeats) {
    const display = document.getElementById('selected-seats-display');
    if (display) {
        if (selectedSeats.size > 0) {
            display.textContent = `已选择 ${selectedSeats.size} 个座位`;
            display.classList.remove('d-none');
        } else {
            display.classList.add('d-none');
        }
    }
    
    // 更新总价
    updateTotalPrice(selectedSeats.size);
}

// 更新总价
function updateTotalPrice(seatCount) {
    const priceElement = document.getElementById('total-price');
    const pricePerSeat = parseFloat(document.getElementById('price-per-seat')?.dataset.price || 0);
    
    if (priceElement && pricePerSeat > 0) {
        const totalPrice = seatCount * pricePerSeat;
        priceElement.textContent = `¥${totalPrice.toFixed(2)}`;
    }
}

// 电影推荐功能
function initMovieRecommendations() {
    const recommendBtn = document.getElementById('get-recommendations');
    if (recommendBtn) {
        recommendBtn.addEventListener('click', function() {
            this.disabled = true;
            this.innerHTML = '<span class="loading"></span> 获取推荐中...';
            
            fetch('/api/recommendations/')
                .then(response => response.json())
                .then(data => {
                    if (data.recommendations) {
                        displayRecommendations(data.recommendations);
                    } else {
                        showAlert('获取推荐失败，请稍后重试', 'warning');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('网络错误，请检查网络连接', 'danger');
                })
                .finally(() => {
                    this.disabled = false;
                    this.innerHTML = '<i class="fas fa-magic me-1"></i>获取推荐';
                });
        });
    }
}

// 显示推荐结果
function displayRecommendations(recommendations) {
    const container = document.getElementById('recommendations-container');
    if (container) {
        container.innerHTML = `
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-magic me-2"></i>AI推荐电影</h5>
                </div>
                <div class="card-body">
                    <pre class="mb-0">${recommendations}</pre>
                </div>
            </div>
        `;
        container.classList.remove('d-none');
    }
}

// 表单验证
function initFormValidation() {
    const forms = document.querySelectorAll('.needs-validation');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(event) {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        });
    });
}

// 动态加载效果
function initFadeInEffects() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in');
            }
        });
    }, observerOptions);
    
    const elements = document.querySelectorAll('.card, .movie-card');
    elements.forEach(el => observer.observe(el));
}

// 显示警告消息
function showAlert(message, type = 'info') {
    const alertContainer = document.createElement('div');
    alertContainer.className = `alert alert-${type} alert-dismissible fade show`;
    alertContainer.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    const container = document.querySelector('.container');
    if (container) {
        container.insertBefore(alertContainer, container.firstChild);
        
        // 自动消失
        setTimeout(() => {
            if (alertContainer.parentNode) {
                alertContainer.remove();
            }
        }, 5000);
    }
}

// 确认对话框
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 格式化价格
function formatPrice(price) {
    return `¥${parseFloat(price).toFixed(2)}`;
}

// 搜索功能增强
function initSearchEnhancement() {
    const searchInput = document.querySelector('input[name="search"]');
    if (searchInput) {
        let searchTimeout;
        
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                if (this.value.length >= 2) {
                    // 可以在这里添加实时搜索功能
                    console.log('搜索:', this.value);
                }
            }, 500);
        });
    }
}

// 图片懒加载
function initLazyLoading() {
    const images = document.querySelectorAll('img[data-src]');
    
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                imageObserver.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
}

// 初始化所有功能
document.addEventListener('DOMContentLoaded', function() {
    initSearchEnhancement();
    initLazyLoading();
}); 